package com.eduagent.xwqeduagent.tools;

import com.eduagent.xwqeduagent.api.imagesearch.so.SoImageSearchApiFacade;
import com.eduagent.xwqeduagent.api.imagesearch.so.model.SoImageSearchResult;
import com.eduagent.xwqeduagent.common.BaseResponse;
import com.eduagent.xwqeduagent.common.ResultUtils;
import com.eduagent.xwqeduagent.exception.ErrorCode;
import com.eduagent.xwqeduagent.exception.ThrowUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.tool.annotation.Tool;
import org.springframework.ai.tool.annotation.ToolParam;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@Component // 添加 @Component 注解使其成为 Spring Bean
public class SamePictureSearchTool {

    @Tool(description = "Search for similar pictures based on a given picture URL. Returns a list of search results.")
    public BaseResponse<List<SoImageSearchResult>> searchSimilarPictures(
            @ToolParam(description = "URL of the picture to search for similar ones") String searchPictureUrl) {

        ThrowUtils.throwIf(searchPictureUrl == null, ErrorCode.PARAMS_ERROR, "图片URL不能为空"); // 建议添加错误信息

        List<SoImageSearchResult> resultList = new ArrayList<>();
        // 这个 start 是控制查询多少页, 每页是 20 条 (或者根据实际API行为调整注释)
        int start = 0;
        int maxResults = 50; // 定义最大结果数量，使逻辑更清晰

        // 添加日志记录
        log.info("开始以图搜图，图片URL: {}", searchPictureUrl);

        while (resultList.size() < maxResults) { // 使用清晰的条件
            List<SoImageSearchResult> tempList;
            try {
                tempList = SoImageSearchApiFacade.searchImage(searchPictureUrl, start);
            } catch (Exception e) {
                // 记录API调用异常
                log.error("调用 SoImageSearchApiFacade.searchImage 失败，URL: {}, start: {}", searchPictureUrl, start, e);
                // 可以选择抛出业务异常或返回错误结果，这里选择返回已有的结果
                break; // 或者 throw new BusinessException(ErrorCode.OPERATION_ERROR, "搜索相似图片失败");
            }

            if (tempList == null || tempList.isEmpty()) { // 增加对null的判断
                log.info("以图搜图 API 返回空结果，URL: {}, start: {}", searchPictureUrl, start);
                break;
            }
            resultList.addAll(tempList);
            start += tempList.size(); // 更新start的方式更准确

            // 防止无限循环，如果API每次都返回数据但resultList.size()没有增长（理论上不会，除非tempList为空）
            if (tempList.isEmpty() && resultList.size() < maxResults) {
                log.warn("API返回空列表，但未达到最大结果数，提前终止搜索，URL: {}, start: {}", searchPictureUrl, start);
                break;
            }
        }

        // 如果结果超过maxResults，进行截断
        if (resultList.size() > maxResults) {
            resultList = resultList.subList(0, maxResults);
        }

        log.info("以图搜图完成，图片URL: {}, 返回结果数量: {}", searchPictureUrl, resultList.size());
        return ResultUtils.success(resultList);
    }
}
